package com.mes.cloud.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mes.cloud.api.dto.request.product.ProductIdentifyProductsAddRequest;
import com.mes.cloud.api.dto.request.product.ProductIdentifyProductsEnableRequest;
import com.mes.cloud.api.dto.request.product.ProductIdentifyProductsPageRequest;
import com.mes.cloud.api.dto.response.product.ProductIdentifyProductsPageDto;
import com.mes.cloud.exception.BaseException;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.ProductIdentifyProductsDao;
import com.mes.cloud.entity.ProductIdentifyProducts;
import com.mes.cloud.entity.ProductLog;
import com.mes.cloud.entity.vo.product.ProductIdentifyProductsPageVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.CommonUtil;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 标识产品关联
 *
 * @author xy
 * @version 2019-08-23 10:37:15
 * @email yuan.xue3@pactera.com
 */
@Service
public class ProductIdentifyProductsService {

    private ProductIdentifyProductsDao productIdentifyProductsDao;

    private IPKeyGenerator ipKeyGenerator;

    private LogService logService;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public ProductIdentifyProductsService(ProductIdentifyProductsDao productIdentifyProductsDao
            , IPKeyGenerator ipKeyGenerator
            , LogService logService) {
        this.productIdentifyProductsDao = productIdentifyProductsDao;
        this.ipKeyGenerator = ipKeyGenerator;
        this.logService = logService;
    }

    /**
     * <分页查列表>
     *
     * @param pageRequest
     * @return JsonResult<CommPager<ProductIdentifyProductsPageDto>>
     * @author xy
     * @date 2019/8/28 15:27
     */
    public JsonResult<CommPager<ProductIdentifyProductsPageDto>> pageList(ProductIdentifyProductsPageRequest pageRequest) {
        Page<ProductIdentifyProductsPageDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());

        //查询条件
        pageRequest.setEnableFlag(Constants.ENABLE_FLAG_YES);
        List<ProductIdentifyProductsPageVo> productIdentifyProductsList = productIdentifyProductsDao.pageList(pageRequest);

        List<ProductIdentifyProductsPageDto> productIdentifyProductsDtoList = new ArrayList<>();
        for (ProductIdentifyProductsPageVo productIdentifyProducts : productIdentifyProductsList) {
            ProductIdentifyProductsPageDto productIdentifyProductsDto = new ProductIdentifyProductsPageDto();
            BeanUtils.copyProperties(productIdentifyProducts, productIdentifyProductsDto);
            productIdentifyProductsDtoList.add(productIdentifyProductsDto);
        }

        CommPager<ProductIdentifyProductsPageDto> pageResult = new CommPager<>(page, productIdentifyProductsDtoList);
        JsonResult<CommPager<ProductIdentifyProductsPageDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);

        return jsonResult;
    }

    /**
     * <新增>
     *
     * @param productIdentifyProductsRequest
     * @return JsonResult
     * @author xy
     * @date 2019/8/28 15:27
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult add(ProductIdentifyProductsAddRequest productIdentifyProductsRequest) {
        //提取保存数据
        dataRepeatCheck(productIdentifyProductsRequest);

        JsonResult jsonResult = new JsonResult();
        //去重后无新增数据,直接返回
        if (CollectionUtils.isEmpty(productIdentifyProductsRequest.getRelateProductIds())) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            return jsonResult;
        }

        List<ProductIdentifyProducts> addList = new ArrayList<>();
        for (String relateProductId : productIdentifyProductsRequest.getRelateProductIds()) {
            ProductIdentifyProducts productIdentifyProducts = new ProductIdentifyProducts();
            productIdentifyProducts.setId(ipKeyGenerator.getGenerateKey());
            productIdentifyProducts.setProductId(productIdentifyProductsRequest.getProductId());
            productIdentifyProducts.setRelateProductId(relateProductId);
            productIdentifyProducts.setUpdateDateStr(DateUtil.updateDateStr());
            productIdentifyProducts.setCreateBy(UserUtil.getCreateByName());
            productIdentifyProducts.setUpdateBy(UserUtil.getUpdateByName());
            productIdentifyProducts.setCreateByNo(UserUtil.getCreateByNo());
            productIdentifyProducts.setUpdateByNo(UserUtil.getUpdateByNo());
            addList.add(productIdentifyProducts);
        }

        int count = productIdentifyProductsDao.batchInsert(addList);
        if (count > 0) {
            for (ProductIdentifyProducts ppc : addList) {
                this.insertLog(ppc.getProductId(), Constants.ADD_LINK_TO_PRODUCT_IDENTIFY);
            }
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * 请求id与存储id比较，去重
     *
     * @param ppc
     * @return void
     * @author xy
     * @date 2019/8/28 15:27
     */
    private void dataRepeatCheck(ProductIdentifyProductsAddRequest ppc) {

        String productId = ppc.getProductId();

        ProductIdentifyProducts queryParams = new ProductIdentifyProducts();
        queryParams.setProductId(productId);
        queryParams.setEnableFlag(Constants.ENABLE_FLAG_YES);

        //通过产品id查询
        List<ProductIdentifyProducts> dbList = productIdentifyProductsDao.select(queryParams);
        //查询是否已存在产品关联数据
        if (!CollectionUtils.isEmpty(dbList)) {
            //db关联产品id set
            Set<String> dbRelateProductIdSet = new HashSet<>();
            //提取关联产品id
            for (ProductIdentifyProducts productIdentify : dbList) {
                dbRelateProductIdSet.add(productIdentify.getRelateProductId());
            }

            //请求List
            List<String> relateProductIdList = ppc.getRelateProductIds();
            //请求关联产品id List 转Set
            Set<String> relateProductIdSet = new HashSet<>(relateProductIdList);
            //去重复
            Set<String> set = CommonUtil.deleteExistId(dbRelateProductIdSet, relateProductIdSet);

            List<String> relateProductIds = new ArrayList<>(set);

            ppc.setRelateProductIds(relateProductIds);

        }
    }

    /**
     * <禁用启用>
     *
     * @param productIdentifyProductsEnableRequest
     * @return JsonResult
     * @author xy
     * @date 2019/8/28 15:26
     */
    public JsonResult updateEnableFlag(ProductIdentifyProductsEnableRequest productIdentifyProductsEnableRequest) {
        productIdentifyProductsEnableRequest.setEnableFlag(Constants.ENABLE_FLAG_NO);
        productIdentifyProductsEnableRequest.setUpdateDateStr(DateUtil.updateDateStr());
        productIdentifyProductsEnableRequest.setUpdateBy(UserUtil.getUpdateByName());
        productIdentifyProductsEnableRequest.setUpdateByNo(UserUtil.getUpdateByNo());

        int count = productIdentifyProductsDao.batchUpdateEnable(productIdentifyProductsEnableRequest);
        JsonResult jsonResult = new JsonResult();
        if (count > 0) {
            // 插入操作日志
            for (String id : productIdentifyProductsEnableRequest.getIds()) {
                this.insertLog(productIdentifyProductsEnableRequest.getProductId(), Constants.REMOVE_LINK_TO_PRODUCT_IDENTIFY);
            }
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * <功能详细描述>
     *
     * @param id,logMessage
     * @return void
     * @author xy
     * @date 2019/8/28 15:26
     */
    @SuppressWarnings("Duplicates")
    private void insertLog(String id, String logMessage) {
        ProductLog productLog = new ProductLog();
        productLog.setProductId(id);
        productLog.setMenuCode(Constants.PRODUCT_MENU_CODE);
        productLog.setLog(logMessage);
        productLog.setId(ipKeyGenerator.getGenerateKey());
        productLog.setUpdateDateStr(DateUtil.updateDateStr());
        productLog.setCreateBy(UserUtil.getCreateByName());
        productLog.setUpdateBy(UserUtil.getUpdateByName());
        productLog.setCreateByNo(UserUtil.getCreateByNo());
        productLog.setUpdateByNo(UserUtil.getUpdateByNo());
        logService.insertProductLog(productLog);
    }
}
